from django.core.management.base import BaseCommand
from elasticsearch import Elasticsearch
from search.sync.course_sync import CourseSync
from search.documents.course import CourseDocument


class Command(BaseCommand):
    help = '同步课程数据到Elasticsearch'

    def add_arguments(self, parser):
        parser.add_argument(
            '--full',
            action='store_true',
            help='执行全量同步',
        )
        parser.add_argument(
            '--init',
            action='store_true',
            help='初始化索引',
        )

    def handle(self, *args, **options):
        if options['init']:
            self.stdout.write('初始化索引...')
            # 删除旧索引（如果存在）
            es = Elasticsearch(['http://localhost:9200'])
            if es.indices.exists(index='course_index'):
                es.indices.delete(index='course_index')
            if es.indices.exists(index='course_index_temp'):
                es.indices.delete(index='course_index_temp')
            # 初始化新索引
            CourseDocument.init()
            self.stdout.write(self.style.SUCCESS('索引初始化完成'))
            return

        sync = CourseSync()

        if options['full']:
            self.stdout.write('开始全量同步...')
            sync.full_sync()
            self.stdout.write(self.style.SUCCESS('全量同步完成'))
        else:
            self.stdout.write('请指定 --full 参数执行全量同步')